package com.ifinc.common.protocol.i8583.field;

import com.ifinc.common.utils.encode.ByteUtil;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * User: luotao
 * Date: 13-11-15
 * Time: 13:41
 */
public class FieldComp extends AbstractField {

    LinkedHashMap<Integer, Field> fields = new LinkedHashMap<Integer, Field>();

    List<Byte> bytes = new ArrayList<Byte>();

    private int subLen = 0;

    public FieldComp() {
        this(0,new Field[]{});
    }



    public FieldComp(int subLen, Field... fields) {
        int i = 0;
        for (Field field : fields) {
            i++;
            this.fields.put(i, field);
        }
        this.subLen = subLen;
    }

    public void addSubField(int subIndex,String srcValue){
        if(subIndex<0||subIndex>subLen){
            throw new RuntimeException("illegal param,subIndex's value must > 0 and < "+subLen);
        }
        Field subField = fields.get(subIndex);
        if(subField==null){
            throw new RuntimeException("subField not exists,subIndex:"+subIndex);
        }
        subField.setSrcValue(srcValue);
        bytes.addAll(ByteUtil.byteArray2List(subField.getSrcBytes()));
        setSrcBytes(ByteUtil.list2ByteArray(bytes));
    }

    @Override
    public byte[] toByte() {
        List<Byte> bytes = new ArrayList<Byte>();
        for (Map.Entry<Integer, Field> entry : fields.entrySet()) {
            Field field = entry.getValue();
            if(field==null){
                continue;
            }
            byte[] bb = entry.getValue().toByte();
            bytes.addAll(ByteUtil.byteArray2List(bb));
        }
        resBytes = ByteUtil.list2ByteArray(bytes);
        setResValue(byte2Str(resBytes));
        return resBytes;
    }

    @Override
    public byte[] toMacByte() {
        return new byte[0];
    }

    @Override
    public String getFieldType() {
        return COMP;
    }

    @Override
    public int toValue(byte[] data, int index) {
        return 0;
    }
}
